package cron

import (
	"github.com/astaxie/beego"
	"github.com/robfig/cron"
	"strings"
)

var IPCountMap = make(map[string]int)
var IPBlackList = make(map[string]bool)

func Init() {
	cr := cron.New()
	//_ = cr.AddFunc("0 * * * * *", everyMin0Task)
	_ = cr.AddFunc("0 0/10 * * * *", clearIPBlackList)
	_ = cr.AddFunc("0/10 * * * * *", clearIPCountMap)
	cr.Start()
}

func PutIp(ip string) bool {
	ipArr := strings.Split(ip, ".")
	ipNet := ""
	if len(ipArr) > 2 {
		ipNet = ipArr[0] + "." + ipArr[1]
	}
	if IPBlackList[ipNet] {
		return false
	}
	IPCountMap[ipNet]++
	checkIpCountMap()
	beego.Debug(IPCountMap)
	beego.Debug(IPBlackList)
	return true
}

func checkIpCountMap() {
	for key, value := range IPCountMap {
		if value >= 5 {
			IPBlackList[key] = true
		}
	}
}

func clearIPCountMap() {
	IPCountMap = map[string]int{}
}

func clearIPBlackList() {
	IPBlackList = map[string]bool{}
}
